package com.cognitran.cssvalidator.ant.output.formatters;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.tools.ant.BuildException;

import com.cognitran.cssvalidator.validation.model.CSSError;
import com.cognitran.cssvalidator.validation.model.CSSValidationResults;
import com.cognitran.cssvalidator.validation.model.CSSWarning;

/**
 * A formatter that outputs W3C styled text.
 * 
 * @author garethf
 */
public class XMLOutputFormatter extends AbstractOutputFormatter
{

	/** The writer that output is written to. */
	private PrintWriter writer = null;
	
	
	/**
	 * {@inheritDoc}
	 */
	public void init()
	{
		try
		{
			final File output = new File(getOutputLocation(), "/report.xml");
			writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output), "utf8"));
		} 
		catch (IOException e) 
		{
			System.err.println(e.getMessage());
			e.printStackTrace();
			// Hmmm, not much to do for now ....
			throw new BuildException("IO problem whilst writing formatted output, error was -> " + e.getMessage(), e);
		}

		writer.println("<validation>");
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	public void writeFormattedOutput(final File source, final CSSValidationResults results) 
	{
		writer.println("  <file url='" + source.toString() + "'>");

		if (results.hasErrors())
		{
			// If there are any errors, write them out ...
			writer.println("    <errors>");
			for (CSSError error : results.getErrors())
			{
				writer.println("      <error line='" + error.getLine() + "' context='" + error.getContext() + "'>");	
				writer.println(error.getMessage());
				writer.println("      </error>");	
			}
			writer.println("    </errors>");
		}
		else
		{
			writer.println("    <errors/>");
		}

		if (results.hasWarnings())
		{
			// If there are any warnings, write them out ...
			writer.println("    <warnings>");
			for (CSSWarning warning : results.getWarnings())
			{
				writer.println("      <warning line='" + warning.getLine() + "'>");	
				writer.println(warning.getMessage());
				writer.println("      </warning>");	
			}
			writer.println("    </warnings>");
		}
		else
		{
			writer.println("    <warnings/>");
		}
		
		writer.println("  </file>");
		writer.flush();
	}

	
	/**
	 * {@inheritDoc}
	 */
	public void cleanup()
	{
		writer.println("</validation>");
		
		writer.flush();
		writer.close();
	}
	
}
